const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const cors = require("cors");
const session = require("express-session");

// 中间件配置顺序很重要，应该在路由之前配置所有中间件
// 1. 跨域中间件
app.use(cors());

// 2. body 解析中间件
app.use(bodyParser.json()); // 添加 JSON 解析
app.use(bodyParser.urlencoded({ extended: true })); // 修改为 true

// 3. 静态文件中间件
app.use('/imgs', express.static(path.join(__dirname, 'public/imgs')));

// 4. session 中间件
app.use(session({
    secret: 'test',
    name: 'name',
    cookie: { maxAge: 60000 },
    resave: false,
    saveUninitialized: true,
}));

// 5. 调试中间件
app.use((req, res, next) => {
    console.log('请求方法:', req.method);
    console.log('请求路径:', req.path);
    console.log('Content-Type:', req.headers['content-type']);
    console.log('请求体:', req.body);
    next();
});

// 数据库连接测试
const db = require('./common/db/db');
db.pool.getConnection((err, connection) => {
    if (err) {
        console.error('数据库连接失败:', err);
        return;
    }
    console.log('数据库连接成功');
    connection.release();
});

// 路由配置 - 必须在所有中间件之后
app.use('/api', require('./router/user.js'));
app.use('/api', require('./router/photo.js'));
app.use('/api', require('./router/email.js'));
app.use('/api', require('./router/banner.js'));
app.use('/api', require('./router/ka_img.js'));

// 移除路由级别的 body-parser 配置
const port = 3000;

app.listen(port, () => {
    console.log("服务启动成功:");
    console.log("http://localhost:" + port);
});
